<template>
  <div class="template_content">
    <!-- 搜索 -->
    <div class="search_box">
      <a-form layout="inline">
        <a-form-item :label="'搜索：'">
          <a-input v-model="searchPage.cardNo" :placeholder="'输入卡号搜索'" allowClear></a-input>
        </a-form-item>
        <a-form-item>
          <a-button icon="search" type="primary" @click="handleSubmit">查询提交</a-button>
        </a-form-item>
      </a-form>
    </div>
      <div class="download_box">
        <a-form layout="inline">
          <a-form-item :label="'生成二维码:'">
            <a-input v-model="number" :placeholder="'请输入需要生成多少个二维码'" allowClear></a-input>
          </a-form-item>
          <a-form-item>
            <a  type="primary" @click="downloadCodeFile">下载压缩二维码</a>
          </a-form-item>
        </a-form>
      </div>

    <!-- 主体内容 -->
    <div class="content_box">
      <a-table
          :columns="columns"
          :dataSource="data"
          :loading="loading"
          :pagination="pagination"
          bordered
          size="small"
          @change="handleTableChange"
      >
        <span slot="cardStatus" slot-scope="cardStatus">
          <a-tag
              :key="cardStatus"
              :color="cardStatus == '0'?'#f50':cardStatus == '1'?'#37ff00':'#108ee9'"
          >{{cardStatus == '0'?"待激活":cardStatus == '1'?"已申请":"已激活"}}</a-tag>
        </span>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
              icon="edit"
              type="primary"
              class="btn_margin"
              @click="activateHairCard(record)"
          >激活</a-button>

          <a-button
              icon="edit"
              type="primary"
              class="btn_margin"
              @click="downloadHairCodeFile(record)"
          >查看二维码</a-button>


        </template>
      </a-table>
    </div>
    <!-- 弹窗 -->
    <a-modal :title="modalTitle" v-model="modalVisible" :footer="null">
      <a-form :form="modalForm" @submit="modalHandleSubmit">
        <a-form-item :label="'名字'" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
              v-decorator="['userName', { rules: [{ required: true, message: '输入名字' }] }]"
              :placeholder="'请输入名字'"
          />
        </a-form-item>
        <a-form-item :label="'手机'" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
              v-decorator="['iphoneNo', { rules: [{ required: true, message: '手机' }] }]"
              :placeholder="'输入手机号'"
          />
        </a-form-item>
        <a-form-item :label="'卡号'" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input v-decorator="[
          'cardNo',
        ]" :placeholder="'卡号'" />
        </a-form-item>

        <a-form-item :label="'总额'" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input v-decorator="[
          'amount',
        ]" :placeholder="'总额'" />
        </a-form-item>
        <a-form-item :label="'状态'" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-select
              v-decorator="[
          'cardStatus',
          { rules: [{ required: true, message: '激活状态' }] },
        ]"
              :placeholder="'激活状态'"
          >
            <a-select-option value="0">待激活</a-select-option>
            <a-select-option value="1">已申请</a-select-option>
            <a-select-option value="2">已激活</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item :label="'激活时间'" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input v-decorator="[
          'activateTime',
        ]" :placeholder="'激活时间'" />
        </a-form-item>
        <a-form-item :label="'申请时间'" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
        <a-input v-decorator="[
          'applyTime',
        ]" :placeholder="'申请时间'" />
      </a-form-item>
        <a-form-item :wrapper-col="{ span: 19, offset: 5 }">
          <a-button type="primary" html-type="submit">保存</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
// 导入接口
import {
  activateHairCard,
  addHairCard,
  deleteHairCard,
  disposereq,
  editHairCard,
  fetchHairCardList
} from "../api/haircard";

let columnsCN = [
  {
    title: "姓名",
    dataIndex: "userName",
    align: "center"
  },
  {
    title: "手机",
    dataIndex: "iphoneNo",
    align: "center"
  },
  {
    title: "卡号",
    dataIndex: "cardNo",
    align: "center",
    scopedSlots: { customRender: "cardNo" }
  },
  {
    title: "金额(元)",
    dataIndex: "amount",
    align: "center"
  },
  {
    title: "状态",
    dataIndex: "cardStatus",
    align: "center",
    scopedSlots: { customRender: "cardStatus" }
  },
  {
    title: "激活时间",
    dataIndex: "activateTime",
    align: "center"
  },
  {
    title: "申请时间",
    dataIndex: "applyTime",
    align: "center"
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    align: "center"
  }
];

export default {
  data() {
    return {
      userName: "",
      loading: true,
      searchPage: {
        start: 0,
        end: 10,
        cardNo: ""
      },
      number:10,
      columns: columnsCN,
      data: [],
      total:0, //总条数
      pagination: {
        current: 1,
        pageSize: 10,
        total: this.total,
        pageSizeOptions: ['10', '20', '30'], // 可选的页面显示条数
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }, // 展示每页第几条至第几条和总数
        hideOnSinglePage: false, // 只有一页时是否隐藏分页器
        showQuickJumper: true, // 是否可以快速跳转至某页
        showSizeChanger: true // 是否可以改变pageSize
      },
      modalVisible: false,
      modalTitle: "添加",
      modalForm: this.$form.createForm(this, { name: "coordinated" }),
      parameters: {
        id:"",
        userName: "",
        iphoneNo: "",
        cardNo: "",
        amount: "",
        cardStatus: "",
        activateTime: "",
        applyTime: ""
      },
      deptOptions: [],
      roleList: "",
      rowData: {},
      fieldNames: { label: "name", value: "id", children: "children" }
    };
  },
  // 创建完毕
  created() {
   fetchHairCardList(this.searchPage).then( res => {
     this.loading = false;
     if (res.code == 0) {
       this.data = res.data.hairCardList;
       this.pagination.total=res.data.total
     } else {
       this.$message.info(res.msg);
     }
   })
       .catch(err => {
         disposereq(this, err);
       });
  },
  methods: {


    // 表格数据变化触发事件
    handleTableChange(pagination) {
      const searchPage = { ...this.searchPage };
      console.log(pagination)
      this.pagination = pagination
      this.loading = true
      const pageNum = pagination.current - 1
      const pageSize = pagination.pageSize
      searchPage.start = pageNum*pageSize;
      searchPage.end  = pageSize;
      searchPage.cardNo   = pagination.cardNo;
      this.loading = true;
      fetchHairCardList(searchPage).then( res => {
        this.loading = false;
        if (res.code == 0) {
          this.data = res.data.hairCardList;
          this.pagination.total=res.data.total
        } else {
          this.$message.info(res.msg);
        }
      })
       .catch(err => {
            disposereq(this, err);
       });
    },
    // 搜索事件
    handleSubmit() {

      const searchPage = { ...this.searchPage };
      this.loading = true;
      fetchHairCardList(searchPage).then( res => {
        this.loading = false;
        if (res.code == 0) {
          this.data = res.data.hairCardList;
          this.pagination.total=res.data.total
        } else {
          this.$message.info(err);
        }
      })
          .catch(err => {
            disposereq(this, err);
          });
    },

    activateHairCard(row){
      activateHairCard(row.id).then(res => {
        this.loading = false;
        if (res.code == 0) {
          this.data = res.data;
          this.$nextTick(() => {
            this.modalForm.setFieldsValue({
              id:res.data.id,
              userName: res.data.userName,
              iphoneNo: res.data.iphoneNo,
              cardNo:res.data.cardNo,
              amount: res.data.amount,
              cardStatus: res.data.cardStatus,
              activateTime:res.data.activateTime ,
              applyTime: res.data.applyTime
            });
            this.rowData =res.data;
          });
        } else {
          this.$message.info(res.msg);
        }
      })

    },
    // 显示对话框
    showModal(row) {
      this.modalVisible = true;
      // 判断添加或者编辑
      if (row == "") {
        this.modalTitle = "添加成功";
        this.modalType = "add";
        this.$nextTick(() => {
          this.modalForm.setFieldsValue({
            id:"",
            userName: "",
            iphoneNo: "",
            cardNo: "",
            amount: "",
            cardStatus: "",
            activateTime: "",
            applyTime: ""
          });
        });
      } else {
        this.modalTitle = "修改成功";
        this.modalType = "edit";
        this.$nextTick(() => {
          this.modalForm.setFieldsValue({
            id:row.id,
            userName: row.userName,
            iphoneNo: row.iphoneNo,
            cardNo:row.cardNo,
            amount: row.amount,
            cardStatus: row.cardStatus,
            activateTime:row.activateTime ,
            applyTime: row.applyTime
          });
          this.rowData = row;
        });
      }
    },
    // 删除行数据
    deleteRow(row) {
      deleteHairCard(row.record.id)
          .then(res => {
            this.loading = false;
            if (res.code == 0) {
              this.$message.success("删除成功");
              const searchPage = { ...this.searchPage };
              this.loading = true;
              this.fetchHairCardList(searchPage);
            } else {
              this.$message.info(err);
            }
          })
          .catch(err => {
            disposereq(this, err);
          });
    },
    // 对话框
    modalHandleSubmit(e) {
      e.preventDefault();
      this.modalForm.validateFields((err, values) => {
        if (!err && this.modalType == "add") {
          addHairCard(values)
              .then(res => {
                if (res.code == 0) {
                  this.modalVisible = false;
                  this.$message.success("创建成功");
                  const searchPage = { ...this.searchPage };
                  this.loading = true;
                  this.getList(searchPage);
                } else {
                  this.$message.info(err);
                }
              })
              .catch(err => {
                this.$message.info(err);
              });
        } else if (!err && this.modalType == "edit") {

          this.rowData.id = values.id;
          this.rowData.userName = values.userName;
          this.rowData.iphoneNo = values.iphoneNo;
          this.rowData.cardNo = values.cardNo;
          this.rowData.amount = values.amount;
          this.rowData.cardStatus = values.cardStatus;
          this.rowData.activateTime = values.activateTime;
          this.rowData.applyTime = values.applyTime;
          editHairCard(this.rowData)
              .then(res => {
                if (res.code == 0) {
                  this.modalVisible = false;
                  this.$message.success("修改成功");
                  const searchPage = { ...this.searchPage };
                  this.loading = true;
                  this.fetchHairCardList(searchPage);
                } else {
                  this.$message.info(err);
                }
              })
              .catch(err => {
                this.$message.info(err);
              });
        }
      });
    },
    downloadCodeFile() {
      this.$axios.request( {
        url:"/admin/downLoadFile",
        baseURL:'http://116.205.138.74:8080',
        params: {
          number:this.number
        },
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        },
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data]);
        const fileName = res.headers["content-disposition"].split(";")[1].split("filename=")[1];
        if ('download' in document.createElement("a")) {
          const link = document.createElement("a");
          link.download = fileName;
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        } else {
          navigator.msSaveBlob(blob, fileName);
        }
      });


    },

    downloadHairCodeFile(record) {
      this.$axios.request( {
        url:"/admin/downLoadHair",
        baseURL:'http://116.205.138.74:8080',
        params: {
          cardNo:record.cardNo
        },
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data]);
        const fileName = res.headers["content-disposition"].split(";")[1].split("filename=")[1];
        if ('download' in document.createElement("a")) {
          const link = document.createElement("a");
          link.download = fileName;
          link.style.display = 'none';
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        } else {
          navigator.msSaveBlob(blob, fileName);
        }
      });


    }







  }
};
</script>
<style>
.search_box {
  width: 100%;
  box-sizing: border-box;
  padding: 14px;
  background-color: #fff;
}

.download_box {
  width: 100%;
  box-sizing: border-box;
  padding: 14px;
  background-color: #fff;
}
.template_content {
  background-color: #f0f2f5;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.content_box {
  width: 100%;
  background-color: #fff;
  margin-top: 10px;
  padding: 14px;
}
.table_top {
  padding-bottom: 14px;
}
.btn_margin {
  margin: 0px 5px;
}
.btn_right_margin {
  margin-right: 10px;
}
</style>
